//
//  ReadingMeterTaskSearchVC.swift
//  Employee
//
//  Created by tancheng on 2018/6/25.
//  Copyright © 2018年 remotevillage. All rights reserved.
//

import Foundation
import UIKit
import MJRefresh
import Moya
import RxSwift

class ReadingMeterTaskSearchVC: BaseVC {
    
    
    
    fileprivate var taskDatas: [ReadingMeterTaskModel] = []
    fileprivate var page = PageModel()
    fileprivate var hearderCancle: Cancellable?
    fileprivate var footerCancle: Cancellable?
    fileprivate var send:ReadingMeterTaskSend = ReadingMeterTaskSend()
    
    fileprivate var customNavigationBar: UIView!
    fileprivate var searchView: SJSearchBar!
    fileprivate var tableView: UITableView!
    
    fileprivate var topLabel: UILabel!
    fileprivate var bottomLabel: UILabel!
    fileprivate lazy var resultView: SectionV = {
        
        let view = SectionV(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 30))
        view.title = ""
        view.backgroundColor = GlobalConfig.BGWhiteColor
        view.titleColor = GlobalConfig.TextLightColor
        return view
        
    }()
    
    fileprivate var disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = GlobalConfig.BGWhiteColor
        
        create()
        searchView.becomeActive()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
        GlobalConfig.baiduStatisticsPageViewStart("抄表任务搜索")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: true)
        GlobalConfig.baiduStatisticsPageViewEnd("抄表任务搜索")
    }
    
    deinit {
        if let temp = hearderCancle { temp.cancel() }
        if let temp = footerCancle { temp.cancel() }
    }
    
}


// MARK: - action

extension ReadingMeterTaskSearchVC {
    
    fileprivate func pullData() {
        
        tableView.mj_footer.isHidden = true
        
        if let _ = tableView.superview {}
        else {
            self.taskDatas = []
            self.page.page = "1"
            self.tableView.reloadData()
        }
        
        if searchView.text.isEmpty {
            
            self.taskDatas = []
            self.page.page = "1"
            self.resultView.title = ""
            self.topLabel.text = ""
            self.bottomLabel.text = ""
            self.tableView.reloadData()
            return
        }
        
        
        if let temp = hearderCancle { temp.cancel() }
        
        
        send.keyword = searchView.text ///
       
        SJApp.showStateBarHUD()
        
       hearderCancle = MeterRequest.shared.getReadingMeterTaskList(send: send, success: { (data, page) in
            
            self.taskDatas = data
            self.page = page
            
            if !self.page.hasData {
                self.topLabel.text = "哎呀!"
                self.bottomLabel.text = "没有找到“\(self.searchView.text)”相关内容"
                self.topLabel.isHidden = false
                self.bottomLabel.isHidden = false
                self.tableView.removeFromSuperview()
                return
            } else {
                self.topLabel.isHidden = true
                self.bottomLabel.isHidden = true
                self.view.addSubview(self.tableView)
            }
            
            self.tableView.mj_footer.isHidden = false
            if self.page.hasNextPage {
                
                self.tableView.mj_footer.endRefreshing()
                
            }
            else { self.tableView.mj_footer.isHidden = true }
            
            self.resultView.title = "共搜索到\(self.page.totalAmount ?? "")个结果"
            self.tableView.reloadData()
            
        }) {
            
        }
        
    }
    
    @objc fileprivate func footerRefresh() {
        
        footerCancle = MeterRequest.shared.getReadingMeterTaskList(send: send, success: { (data, page) in
            
            self.taskDatas += data
            self.page = page
            
            if self.page.hasNextPage { self.tableView.mj_footer.endRefreshing()}
            else { self.tableView.mj_footer.isHidden = true }
            self.tableView.reloadData()
        }){}
    }
    
}

// MARK: - UITableViewDataSource

extension ReadingMeterTaskSearchVC : UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return taskDatas.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: ReadingMeterTaskCell.reuseIdentifer, for: indexPath) as! ReadingMeterTaskCell
        
        cell.model = taskDatas[indexPath.row]
        
        return cell
        
    }
    
}

// MARK: - UITableViewDelegate

extension ReadingMeterTaskSearchVC : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return taskDatas[indexPath.row].cooperation ? 116+5 : 92+5
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        SJApp.endEdit()
        
        let vc = ReadingMeterDetailVC()
        
        vc.taskId = taskDatas[indexPath.row].taskId
        
        navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return resultView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    
}

// MARK: - SJSearchBarDelegate

extension ReadingMeterTaskSearchVC: SJSearchBarDelegate {
    
    func didBeaginSearch() {
        
    }
    
    func didEndSearch() {
        
        navigationController?.popViewController(animated: true)
        
    }
    
    func didChange(text: String) {
        
        
        
//        if hearderCancle != nil && !(hearderCancle!.isCancelled) {
//            hearderCancle?.cancel()//取消之前没有没有完成的任务
//        }
        
        let t = DispatchTime.now() + 0.3
        DispatchQueue.main.asyncAfter(deadline: t) {
            self.pullData()
        }
    }
    
}

// MARK: - fileprivate

extension ReadingMeterTaskSearchVC {
    
    fileprivate func create() {
        
        customNavigationBar = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 64))
        customNavigationBar.backgroundColor = UIColor.white
        view.addSubview(customNavigationBar)
        
        searchView = SJSearchBar()
        searchView.backgroundColor = UIColor.white
        searchView.textFieldBackgroundColor = GlobalConfig.BGWhiteColor
        searchView.placeholder = "房号/表号"
        searchView.sj.top = 20
        searchView.delegate = self
        customNavigationBar.addSubview(searchView)
        
        
        topLabel = UILabel()
        view.addSubview(topLabel)
        topLabel.font = GlobalConfig.system15Font
        topLabel.textColor = GlobalConfig.BGSkyBlueColor
        topLabel.snp.makeConstraints { (make) in
            
            make.centerX.equalToSuperview()
            make.top.equalTo(100)
            
        }
        
        bottomLabel = UILabel()
        view.addSubview(bottomLabel)
        bottomLabel.font = GlobalConfig.system15Font
        bottomLabel.textColor = GlobalConfig.BGSkyBlueColor
        bottomLabel.numberOfLines = 0
        bottomLabel.textAlignment = .center
        bottomLabel.snp.makeConstraints { (make) in
            
            make.left.equalTo(50)
            make.right.equalTo(-50)
            make.centerX.equalToSuperview()
            make.top.equalTo(topLabel.snp.bottom).offset(15)
            
        }
        
        tableView = UITableView()
        tableView.backgroundColor = GlobalConfig.BGWhiteColor
        tableView.frame = CGRect(x: 0, y: 64, width: UIScreen.width, height: UIScreen.height - UIScreen.navBarHeight)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
        footerView.backgroundColor = GlobalConfig.BGWhiteColor
        tableView.tableFooterView = footerView
        tableView.register(UINib.init(nibName: "ReadingMeterTaskCell", bundle: nil), forCellReuseIdentifier: ReadingMeterTaskCell.reuseIdentifer)
        
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(footerRefresh))
        tableView.mj_footer.isHidden = true
        
        view.addSubview(tableView)
        
        
    }
    
}


